//
//  YSGHomeViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/11/17.
//  Copyright © 2020 QDSG. All rights reserved.
//

import Foundation
import HandyJSON
import RxSwift
import YSGFramework

class YSGHomeViewModel: NSObject {
    var departmentsList: [YSGDepartment] = []
    var doctorsList: [DoctorReserveModel] = []
    var topBannersList: [YSGBanner] = []
    var centerBannersList: [YSGBanner] = []
    
    private var error: String?
    
    var updateClosure: ((String?) -> Void)?
    
    func doctorVm() -> DoctorReserveViewModel {
        return DoctorReserveViewModel(models: doctorsList)
    }
    
    func departmentVm() -> YSGDepartmentViewModel {
        return YSGDepartmentViewModel(models: departmentsList)
    }
    
    func topBannerVm() -> YSGBannerViewModel {
        return YSGBannerViewModel(models: topBannersList)
    }
    
    func centerBannerVm() -> YSGBannerViewModel {
        return YSGBannerViewModel(models: centerBannersList)
    }
    
    /// 获取首页数据
    func getHomeData() {
        let requestGroup = DispatchGroup()
        let requestQueue = DispatchQueue(label: "home_request", qos: .default, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil) // 并行队列
        
        requestGroup.enter()
        requestQueue.async {
            self.getBannerList { requestGroup.leave() }
        }
        
        requestGroup.enter()
        requestQueue.async {
            self.getDepartments { requestGroup.leave() }
        }
        
        requestGroup.enter()
        requestQueue.async {
            self.getRecommendDoctors { requestGroup.leave() }
        }
        
        requestGroup.notify(queue: requestQueue) {
            YSGLog("首页请求全部完成：+++++++++++++++++")
            self.updateClosure?(self.error)
        }
    }
    
    /// 获取科室列表 flag: 0-推荐科室 1-全部科室
    private func getDepartments(finished: @escaping () -> Void) {
        let params = ["flag": 0]
        HttpTool.shared.request(target: ApiManager.getDepartmentList(paras: params), success: { (json, code) in
            YSGLog(json)
            if let models = JSONDeserializer<YSGDepartment>.deserializeModelArrayFrom(json: json["data"].description) as? [YSGDepartment] {
                self.error = nil
                self.departmentsList = models
            } else {
                self.error = "数据解析错误，请重试"
            }
            finished()
        }) { error in
            YSGLog(error)
            self.error = error?.debugDescription
            finished()
        }
    }
    
    /// 获取推荐医生
    private func getRecommendDoctors(finished: @escaping () -> Void) {
        let params: [String: Any] = [
            "deptId": "",
            "diagType": 1,
            "content": "",
            "scheduleTime": "",
            "timeInterval": "",
            "current": 1,
            "size": 10,
            "code": "",
            "isPrescription": "",
            "isRecommend": 1,
        ]
        
        HttpTool.shared.request(api: ApiManager.doctorReserveList_doctor(paras: params), model: CLBasicArrayDataModel<DoctorReserveModel>.self, completeHandle: {
                    switch $0 {
                    case .success(let model):
                        self.doctorsList = model.data?.records ?? []
                    case .failure(let error):
                        self.error = error.errorValue
                    }
                    finished()
                })
        
    }
    
    /// 获取首页轮播图
    private func getBannerList(finished: @escaping () -> Void) {
        HttpTool.shared.request(target: ApiManager.bannerList, success: { (json, code) in
            YSGLog(json)
            if let headers = JSONDeserializer<YSGBanner>.deserializeModelArrayFrom(json: json["data"]["header"].description) as? [YSGBanner],
                let middles = JSONDeserializer<YSGBanner>.deserializeModelArrayFrom(json: json["data"]["middle"].description) as? [YSGBanner] {
                self.error = nil
                self.topBannersList = headers
                self.centerBannersList = middles
            } else {
                self.error = "数据解析错误，请重试"
            }
            finished()
        }) { error in
            self.error = error.debugDescription
            finished()
        }
    }
}
